package com.novelot.plugin.gradle

import com.google.gson.Gson
import java.io.File
import java.nio.charset.Charset
import java.util.*

fun Node.traversal() {
    System.out.println("${this.level}:${this.path}:${this.lastModified}")
    if (this.childs.isNotEmpty()) {
        childs.forEach {
            
            it.traversal()
        }
    }
}

/**
 * 深度优先
 */
fun Node.depthFirstSearch() {
    System.out.println("${this.level}:${this.path}:${this.lastModified}")
    if (this.childs.isNotEmpty()) {
        childs.forEach {
            it.traversal()
        }
    }
}

/**
 * 宽度优先遍历
 */
fun Node.breadthFirstSearch() {
    val queue = LinkedList<Node>()
    queue.add(this)

    while (queue.isNotEmpty()) {
        val node = queue.removeFirst()
        System.out.println("${node.level}:${node.path}:${node.lastModified}")
        if (node.childs.isNotEmpty()) {
            queue.addAll(node.childs)
        }
    }
}

/**
 * 宽度优先遍历
 */
fun Node.breadthFirstSearch(block: (Node) -> Unit) {
    val queue = LinkedList<Node>()
    queue.add(this)

    while (queue.isNotEmpty()) {
        val node = queue.removeFirst()
        block(node)
        if (node.childs.isNotEmpty()) {
            queue.addAll(node.childs)
        }
    }
}

/**
 * 保存到磁盘
 */
fun Node.saveToDisk(path: String) {
    val file = File(path)
    if (!file.exists()) {
        file.parentFile.mkdirs()
        file.createNewFile()
    }

    file.writeText(Gson().toJson(this), Charset.forName("UTF-8"))
}

fun File.loadToNode(node: Node) {

    val queue = LinkedList<File>()
    queue.add(this)

    val qNode = LinkedList<Node>()
    qNode.add(node)

    while (queue.isNotEmpty()) {
        val f = queue.removeFirst()
        val n = qNode.removeFirst();
        n.path = f.absolutePath
        n.lastModified = f.lastModified()

        if (f.isDirectory) {
            f.listFiles().forEach {
                queue.add(it)
                val child = Node(level = n.level + 1)
                qNode.add(child)
                n.childs.add(child)
            }
        }
    }
}

fun Node.findNodeByPath(path: String): Node? {
    if (this.path == path) return this

    return null
}








